<?php

namespace App\Extend;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * undocumented class
 *
 * @package default
 * @author
 **/
class Payssion
{
    protected $apiUrl = 'https://www.payssion.com';
    protected $appKey;
    protected $secretKey;

    public function __construct()
    {
        $this->appKey = env('PAYSSION_API_KEY');
        $this->secretKey = env('PAYSSION_SECRET_KEY');
    }

    /**
     * Get account detail information
     *
     * @return string
     * @author
     **/
    public function getPaymentSign($pm_id, $amount, $currency, $order_id): string
    {
        $msg = implode('|', [$this->appKey, $pm_id, $amount, $currency, $order_id, $this->secretKey]);
        return md5($msg);
    }

    /**
     * Get account detail information
     *
     * @return string
     * @author
     **/
    public function getNotifySign($pm_id, $amount, $currency, $order_id, $state): string
    {
        $msg = implode('|', [$this->appKey, $pm_id, $amount, $currency, $order_id, $state, $this->secretKey]);
        return md5($msg);
    }

    /**
     * Get account detail information
     *
     * @return array|false
     * @author
     **/
    public function createPayment($amount, $order_id, $desc, $currency = 'USD', $return_url = '')
    {
        $pm_id = 'alipay_cn';
        $sign = $this->getPaymentSign($pm_id, $amount, $currency, $order_id);
        $params = [
            'api_key' => $this->appKey,
            'pm_id' => $pm_id,
            'amount' => $amount,
            'currency' => $currency,
            'description' => $desc,
            'order_id' => $order_id,
            'api_sig' => $sign,
            'return_url' => $return_url,
        ];
        $apiUrl = $this->apiUrl . '/api/v1/payments';
        $response = Http::post($apiUrl, $params);
        $result = $response->json();
        Log::info('Payssion createPayment result：' . json_encode($result));
        return $result;
    }

    /**
     * Get account detail information
     *
     * @return array|false
     * @author
     **/
    public function paymentDetails($order_id, $transaction_id)
    {
        $msg = implode('|', [$this->appKey, $transaction_id, $order_id, $this->secretKey]);
        $sign = md5($msg);
        $params = [
            'api_key' => $this->appKey,
            'transaction_id' => $transaction_id,
            'order_id' => $order_id,
            'api_sig' => $sign
        ];
        $apiUrl = $this->apiUrl . '/api/v1/payment/details';
        $response = Http::post($apiUrl, $params);
        $result = $response->json();
        Log::info('Payssion createPayment result：' . json_encode($result));
        return $result;
    }
} // END class
